import {Component, OnInit, OnDestroy, ViewChild, ElementRef, SimpleChange, ViewChildren} from '@angular/core';
import {TransformerComponent} from '../boxsubstation/transformer/transformer.component';
import {LimitedFarm} from '../main/limited-farm';
import {DataSourceService} from '../../../service/data-source/data-source.service';
import {ApplicationService} from '../../../service/application.service';
import {Router, ActivatedRoute} from '@angular/router';
import {Http} from '@angular/http';
import {DatePipe} from '@angular/common';
import {PhaseService} from '../../../service/phase.service';
import {DeviceService} from '../../../service/device.service';
import {Farm} from '../../../entity/farm.model';
import {Device} from '../../../entity/device.model';
import {Phase} from '../../../entity/phase.model';
import {LimitedPhases} from '../turbine-list/limited-phases';
import {LimitedTransformer} from '../boxsubstation/limited-transformer';
import {TurbStatus} from '../../../entity/turbstatus.model';
import {List} from 'linqts';
import {FarmCategoryEnum} from '../../common/device-tag-selector/farm-category.enum';
import {InterceptorService} from '../../../service/interceptor/interceptor-service';

@Component({
  selector: 'app-boxsubstation',
  templateUrl: './boxsubstation.component.html',
  styleUrls: ['./boxsubstation.component.css']
})
export class BoxSubStationComponent implements OnInit {
  @ViewChildren(TransformerComponent)
  TransformerComp: TransformerComponent[];

  //当前风场
  public currentFarm: LimitedFarm;
  farm: Farm;
  farmId: number = 0;
  active: number = null;
  //风场类别
  farmCategory: FarmCategoryEnum = FarmCategoryEnum.photovoltaic;
  /**
   * 设备列表
   */
  devices: Device[] = [];

  /**
   * 箱变数据
   */
  public limitedTransformers: LimitedTransformer[] = [];

  /**
   * 分期数据
   */
  public limitedPhases: LimitedPhases[] = [];
  public tempLimitedPhases: LimitedPhases[] = [];

  /**
   * 所有选中项对应的箱变列表
   */
  public allCheckTransformerList: LimitedTransformer[] = [];

  /**
   * 数据源服务
   */
  private dataSource: DataSourceService;
  /**
   * 倍率
   */
  public ratio: number = 1;

  /**
   * 所有选中的箱变及区域
   */
  allCheckTransformerSubArrayList: any[] = []
  /**
   * 区域Id集合
   */
  allCheckTransformerSubArrayIds: number[] = []
  /**
   * 是否显示
   */
  public showDetail: boolean;

  public currentBoxstation: Device = null;


  constructor(
    private application: ApplicationService,
    private activatedRoute: ActivatedRoute,
    private http: InterceptorService,
    private router: Router,
    private datePipe: DatePipe,
    private phaseService: PhaseService,
    private deviceService: DeviceService,
  ) {
  }

  ngOnInit() {
    this.activatedRoute.params.subscribe((params: { farmId: number }) => {
      if (params.farmId) {
        this.farmId = params.farmId;
      }
    });
    if (this.application.currentApplicationParams && this.application.currentApplicationParams['ratio']) {
      this.ratio = Number(this.application.currentApplicationParams['ratio'].paramValue);
    }
  }

  //销毁指令
  ngOnDestroy(): void {
    if (this.dataSource != null)
      this.dataSource.dispose();
  }

  /**
   * 风场选中项变化
   */
  public onChangeFarm(farm: Farm) {
    if (farm != null) {
      this.active = null;
      this.loadData(farm);
    }
  }

  /**
   * 加载数据
   */
  private loadData(farm: Farm) {
    this.farm = farm;
    if (this.dataSource != null) {
      this.dataSource.dispose();
    }
    this.dataSource = new DataSourceService(this.http, this.datePipe);
    this.createLimitedFarm(farm);

    let phaseGet: Promise<Phase[]> = this.phaseService.getPhasesByfarmId(farm.farmId);//通过farmId获取的分期
    let deviceGet: Promise<Device[]> = this.deviceService.getBoxSubstationsByFarmId(farm.farmId);//通过farmId获取的设备列表
    // let turbstatusGet: Promise<TurbStatus[]> = this.TurbStatusService.getInverterStatus();//逆变器状态列表
    Promise.all([phaseGet, deviceGet])
      .then(res => {
        if (res[1]) {
          this.devices = [...res[1]]
        }
        this.createLimitedPhases(res[0], res[1]);
        this.createLimitedDevice(res[1]);
        // this.createLimitedTransformerStatus(res[2]);
        //开始推数据
        this.dataSource
          .begin()
          .subscribe(
            next => {
              this.TransformerComp.forEach(val => {
                val.initData()
              })
            },
            error => {
              console.log('app-box-station-list', error);
            });
      })
      .catch(error => {
        console.log('app-box-station-list', error);
      });
  }

  /**
   * 创建风场模型
   */
  private createLimitedFarm(farm: Farm) {
    if (farm != null) {
      let PowerDay = this.application.tagDict['PowerDay'];//日发电量
      let radiantQuantity = this.application.tagDict['FSL'];//辐射量
      let Power = this.application.tagDict['Power'];//有功功率
      let Communication = this.application.tagDict['YC36'];//总发电量
      // console.log(Communication,Power)
      //创建风场数据模型
      this.currentFarm = new LimitedFarm();
      this.currentFarm.farmId = farm.farmId;
      this.currentFarm.farmCode = farm.farmCode;
      this.currentFarm.farmName = farm.farmName;
      this.currentFarm.farmCategory = farm.farmCategory;
      this.currentFarm.posx = farm.posx;
      this.currentFarm.posy = farm.posy;
      this.currentFarm.simpleCode = farm.simpleCode;
      this.currentFarm.capacity = farm.capacity;
      this.currentFarm.productionDate = farm.productionDate;
      this.currentFarm.totalTurbine = farm.totalTurbine;

      //创建实时数据点
      this.currentFarm.powerDay = this.dataSource.binding([farm.farmCode], PowerDay);
      this.currentFarm.radiantQuantity = this.dataSource.binding([farm.farmCode], radiantQuantity);
      this.currentFarm.totalPower = this.dataSource.binding([farm.farmCode], Power);
      this.currentFarm.communication = this.dataSource.binding([farm.farmCode], Communication);
    }

  }

  /**
   * 创建分期
   */
  private createLimitedPhases(phases: Phase[], device: Device[]) {
    if (!phases || !device) return false;

    this.limitedPhases = [];
    let GridMerPower = this.application.tagDict['YC19'];//并网有功P
    let GriReaPower = this.application.tagDict['YC34'];//并网无功Q GriReaPower
    let powerDay = this.application.tagDict['YC35'];//日发电量
    let WindSpeed = this.application.tagDict['MeanWindSpeed'];
    let Power = this.application.tagDict['Power'];
    // console.log(GridMerPower,GriReaPower,powerDay,this.currentFarm)
    phases.forEach(phase => {
      let limitedPhase: LimitedPhases = {
        id: phase.phaseId,
        name: phase.phaseName,
        value: device.filter(o => o.phaseId == phase.phaseId).length,
        powers: this.dataSource.binding([this.currentFarm.farmCode, phase.phaseCode], Power),//有功功率
        powerDay: this.dataSource.binding([this.currentFarm.farmCode, phase.phaseCode], powerDay),//日发电量
        GridMerPower: this.dataSource.binding([this.currentFarm.farmCode, phase.phaseCode], GridMerPower),//并网有功P
        GriReaPower: this.dataSource.binding([this.currentFarm.farmCode, phase.phaseCode], GriReaPower),//并网无功Q
        isChecked: false
      };
      this.limitedPhases.push(limitedPhase)
    })
    this.tempLimitedPhases = [...this.limitedPhases];
  }

  /**
   * 创建设备状态
   *
   */

  /**
   private createLimitedTransformerStatus(turbStatus: TurbStatus[]) {
    if (!turbStatus) return false;
    this.limitedTurbstatus = [];
    turbStatus.forEach(turbStatu => {
      let limitedTurbstatu = {
        id: turbStatu.statusId,
        name: turbStatu.statusName,
        value: turbStatu.statusValue,
        color: turbStatu.statusColor,
        tole: 0,
        isChecked: false,
      }
      this.limitedTurbstatus.push(limitedTurbstatu)
    })
  }
   */
  /**
   * 创建设备模型
   */
  private createLimitedDevice(devices: Device[]) {

    if (!devices) return false
    this.limitedTransformers = [];
    if (this.currentFarm != null) {
      let GriCurrentA1 = this.application.tagDict['xbGriCurrentA1'];//电流1
      let GriVoltageA1 = this.application.tagDict['xbGriVoltageA1'];//电压1
      let ActivePower1 = this.application.tagDict['xbActivePower1'];//有功功率1
      let xbGriReaPower1 = this.application.tagDict['xbGriReaPower1'];//无功功率1

      let powerDay = this.application.tagDict['YC35'];//日发电量
      let TurbineStatus = this.application.tagDict['TurbineStatus'];//设备状态
      let subState = this.application.tagDict['GP'];
      devices.forEach(device => {
        device.farmName = this.farm.farmName;
        let limitedTransformer: LimitedTransformer = {
          name: device.deviceName,
          GriCurA: this.dataSource.binding([this.currentFarm.farmCode, device.deviceCode], GriCurrentA1),
          GriVolA: this.dataSource.binding([this.currentFarm.farmCode, device.deviceCode], GriVoltageA1),
          griPower: this.dataSource.binding([this.currentFarm.farmCode, device.deviceCode], ActivePower1),
          GriReaPower: this.dataSource.binding([this.currentFarm.farmCode, device.deviceCode], xbGriReaPower1),

          turbineStatus: this.dataSource.binding([this.currentFarm.farmCode, device.deviceCode], TurbineStatus),
          turbStatusColor: '#23d678',
          phaseId: device.phaseId,
          circuitId: device.circuitId,
          device: device,
          turbSubState: this.dataSource.binding([this.currentFarm.farmCode, device.deviceCode], subState),
          powerDay: this.dataSource.binding([this.currentFarm.farmCode, device.deviceCode], powerDay),
          // GridMerPower: this.dataSource.binding([this.currentFarm.farmCode, device.deviceCode], GridMerPower),

          subArraryId: device.subArrayId,
          subArrayName: device.subArrayName,
        }
        this.limitedTransformers.push(limitedTransformer);
      })
    }

    this.allCheckTransformerList = this.limitedTransformers;

    //------------------
    this.allCheckTransformerSubArrayList = [];
    this.allCheckTransformerSubArrayIds = [];
    this.allCheckTransformerList.forEach(checkDevice => {
      this.allCheckTransformerSubArrayIds.push(checkDevice.subArraryId)
    })
    this.allCheckTransformerSubArrayIds = Array.from(new Set(this.allCheckTransformerSubArrayIds));
    this.allCheckTransformerSubArrayIds.forEach(id => {
      this.allCheckTransformerSubArrayList.push(this.allCheckTransformerList.filter(a => a.subArraryId == id))
    })
    //------------------

  }

  /**
   * 分期列表点击事件
   */
  public phaseClick(e: any, phase: LimitedPhases) {
    phase.isChecked = phase.isChecked ? false : true;
    this.getDeviceList();
  }

  private getDeviceList() {
    let checkTurPhaseList: LimitedPhases[] = [];
    checkTurPhaseList = this.tempLimitedPhases.filter(o => o.isChecked);  //过滤选中的分期
    if (checkTurPhaseList.length > 0) {
      //将本地风机集合放入临时变量中
      let listTemp = [...this.limitedTransformers];
      let list = new List(checkTurPhaseList).Select(o => o.id).ToList();
      listTemp = listTemp.filter(o => list.Contains(o.phaseId));
      this.allCheckTransformerList = listTemp;
    } else {
      this.allCheckTransformerList = this.limitedTransformers;
    }
  }

  /**
   * 双击
   * @param {ConvergenceBox} convergenceBox
   * @memberof ConvergenceboxListComponent
   */
  ondblclick(item: Device) {
    this.currentBoxstation = item;
    this.showDetail = true;
  }

  /**
   * 点击关闭
   *
   * @memberof ConvergenceboxViewComponent
   */
  onColse() {
    this.showDetail = false;
  }
}


// WEBPACK FOOTER //
// ./src/app/module/monitor/boxsubstation/boxsubstation.component.ts
